package com.qssoft.cqry.common.shardingsphere.ds;

import cn.hutool.core.util.StrUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * @author HuaQiao.Deng
 * @Description:
 * @date 2021/7/7 10:02
 */
public class DynamicDSourceAnnotationInterceptor implements MethodInterceptor {

    private DynamicDSourceClassResolver dynamicDSourceClassResolver = new DynamicDSourceClassResolver();

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("DynamicDSourceAnnotationInterceptor >>> ");
        try {
            //不解析方法,只针对类...
            Object targetObject = invocation.getThis();
            Method method = invocation.getMethod();
            //Class<?> targetClass = targetObject.getClass();
            //String dsType = findDataSourceAttribute(targetClass);
            String dsType = dynamicDSourceClassResolver.findDSKey(method, targetObject);
            if(StrUtil.isNotBlank(dsType)) {
                DynamicDataSourceContextHolder.setDataSourceType(dsType);
            }
            return invocation.proceed();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }


}
